package com.witmore.skyline.web.service.third.tplink;

import com.alibaba.fastjson.JSONObject;
import com.witmore.skyline.web.service.third.constants.ApiTpLinkClientConstant;
import com.witmore.skyline.web.service.third.tplink.dto.DeviceResultDTO;
import com.witmore.skyline.web.service.third.tplink.dto.DeviceInfoResponseDTO;
import com.witmore.skyline.web.service.third.tplink.dto.TpResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.TreeMap;

/**
 * Description: ApiCatchUrlClient
 * <p>
 * * 抓图：
 * * 1.调用1.4.9.2提交设备抓图任务接口提交任务；
 * * 2.调用1.4.9.5查询任务详情接口判断任务是否成功；
 * * 3.如果抓图任务执行成功，调用1.4.9.6分页查询任务文件列表接口获取文件列表（需要下载文件时传入参数urlRequired需要为true）；
 * * 4.将1.4.9.6分页查询任务文件列表接口返回参数中的url复制到浏览器或者使用下载工具下载文件。
 * * 任务管理：
 * * 1.调用1.4.9.4分页查询任务列表接口查询提交过哪些抓图任务；
 * * 2.调用1.4.9.7删除云录制文件接口删除无用文件，节省空间。
 * <p>
 * Author: 豆子高
 * Date: 2025/3/13 17:24
 */
@Slf4j
public class ApiCaptureUrlClient {

    /**
     * 1.4.9.2 提交设备抓图任务
     * 抓图任务: {"result":{"taskId":"3362560"},"error_code":0}
     */
    public static TpResultDTO submitCaptureImageTask(String cameraSn) {
        try {
            // 请求体内容
            String payload = "{\"qrCode\": \"" + cameraSn + "\", \"channelId\": 1,\"type\":1}";
            TreeMap<String, String> headerTreeMap = ApiTPClient.authorizationReady(ApiTpLinkClientConstant.SUBMIT_CAPTURE_IMAGE_TASK_PATH, payload);
            String response = ApiTPClient.sendPost(ApiTpLinkClientConstant.SUBMIT_CAPTURE_IMAGE_TASK_URL, payload, headerTreeMap);
            if (StringUtils.isNotEmpty(response)) {
                return JSONObject.parseObject(response, TpResultDTO.class);
            }
        } catch (Exception e) {
            log.error("提交抓图任务失败: 失败原因：{}", e.getMessage());
        }
        return null;
    }

    public static void main(String[] args) {
        TpResultDTO tpResultDTO = submitCaptureImageTask("0D58DFBB27BF1D17B");
        System.out.println(tpResultDTO);
    }

    /**
     * 1.4.9.5查询任务详情接口
     * {"result":{"taskId":"3362560","type":1,"state":11,"fileCount":0,"totalBytes":0,"errorMsg":"device offline","createTime":"20250313170741","error_code":-80327},"error_code":0}
     */
    public static TpResultDTO getTaskInfo(String taskId) {
        try {
            // 请求体内容
            String payload = "{\"taskId\": \"" + taskId + "\"}";
            TreeMap<String, String> headerTreeMap = ApiTPClient.authorizationReady(ApiTpLinkClientConstant.GET_TASK_INFO_PATH, payload);
            String response = ApiTPClient.sendPost(ApiTpLinkClientConstant.GET_TASK_INFO_URL, payload, headerTreeMap);
            if (StringUtils.isNotEmpty(response)) {
                return JSONObject.parseObject(response, TpResultDTO.class);
            }
        } catch (Exception e) {
            log.error("查询任务详情失败: 失败原因：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 1.4.9.6分页查询任务文件列表接口
     */
    public static TpResultDTO getTaskFilePage(String taskId) {
        try {
            String payload3 = "{\"taskId\": " + taskId + ",\"pageIndex\": 0,\"pageSize\": 10,\"urlRequired\": true}";
            TreeMap<String, String> headerTreeMap3 = ApiTPClient.authorizationReady(ApiTpLinkClientConstant.GET_TASK_FILE_PAGE_PATH, payload3);
            String response = ApiTPClient.sendPost(ApiTpLinkClientConstant.GET_TASK_FILE_PAGE_URL, payload3, headerTreeMap3);
            if (StringUtils.isNotEmpty(response)) {
                return JSONObject.parseObject(response, TpResultDTO.class);
            }
        } catch (Exception e) {
            log.error("分页查询任务文件列表接口失败: 失败原因：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 1.4.9.4分页查询任务列表接口
     */
    public static TpResultDTO getTaskPage() {
        try {
            String payload4 = "{\"pageIndex\": 0,\"pageSize\": 10}";
            TreeMap<String, String> headerTreeMap4 = ApiTPClient.authorizationReady(ApiTpLinkClientConstant.GET_TASK_PAGE_PATH, payload4);
            String response = ApiTPClient.sendPost(ApiTpLinkClientConstant.GET_TASK_PAGE_URL, payload4, headerTreeMap4);
            if (StringUtils.isNotEmpty(response)) {
                return JSONObject.parseObject(response, TpResultDTO.class);
            }
        } catch (Exception e) {
            log.error("分页查询任务列表接口失败：失败原因：{}", e.getMessage());
        }
        return null;
    }


    /**
     * 1.4.9.7删除云录制文件接口
     */
    public static TpResultDTO deleteFile(String fileId) {
        try {
            String payload5 = "{\"fileId\": " + fileId + "}";
            TreeMap<String, String> headerTreeMap5 = ApiTPClient.authorizationReady(ApiTpLinkClientConstant.DELETE_FILE_PATH, payload5);
            String response = ApiTPClient.sendPost(ApiTpLinkClientConstant.DELETE_FILE_URL, payload5, headerTreeMap5);
            if (StringUtils.isNotEmpty(response)) {
                return JSONObject.parseObject(response, TpResultDTO.class);
            }
        } catch (Exception e) {
            log.error("删除云录制文件接口失败：失败原因：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 1.4.3.3.1获取设备详细信息
     */
    public static DeviceResultDTO getDeviceInfo(String cameraSn) {
        try {
            String payload = "{\"qrCode\": \"" + cameraSn + "\", \"channelId\": 1}";
            TreeMap<String, String> headerTreeMap = ApiTPClient.authorizationReady(ApiTpLinkClientConstant.GET_DEVICE_INFO_PATH, payload);
            String response = ApiTPClient.sendPost(ApiTpLinkClientConstant.GET_DEVICE_INFO_URL, payload, headerTreeMap);
            if (StringUtils.isNotEmpty(response)) {
                // 解析响应为包装结构
                DeviceInfoResponseDTO responseDTO = JSONObject.parseObject(response, DeviceInfoResponseDTO.class);
                if (responseDTO != null) {
                    // 检查错误码
                    if (responseDTO.getError_code() != null && responseDTO.getError_code() == 0) {
                        // 成功时返回设备详情
                        DeviceResultDTO result = responseDTO.getResult();
                        int status = 0;
                        // 设备状态转换
                        if (result.getDeviceStatus() == 1) {
                            status = 1;
                        }
                        result.setDeviceStatus(status);
                        return responseDTO.getResult();
                    } else {
                        log.error("TPLink获取设备详细信息失败 - 摄像头SN: {}, 错误码: {}", cameraSn, responseDTO.getError_code());
                        return null;
                    }
                } else {
                    log.error("TPLink响应解析失败 - 摄像头SN: {}, 响应内容: {}", cameraSn, response);
                    return null;
                }
            }
        } catch (Exception e) {
            log.error("获取设备详细信息异常 - 摄像头SN: {}, 异常信息: {}", cameraSn, e.getMessage());
        }
        return null;
    }

    /**
     * 1.4.3.3.8修改设备名称
     */
    public static TpResultDTO updateDeviceName(String cameraSn, String deviceName) {
        try {
            String payload = "{\"qrCode\": \"" + cameraSn + "\", \"channelId\": 1, \"deviceName\": \"" + deviceName + "\"}";
            TreeMap<String, String> headerTreeMap = ApiTPClient.authorizationReady(ApiTpLinkClientConstant.UPDATE_DEVICE_NAME_PATH, payload);
            String response = ApiTPClient.sendPost(ApiTpLinkClientConstant.UPDATE_DEVICE_NAME_URL, payload, headerTreeMap);
            if (StringUtils.isNotEmpty(response)) {
                return JSONObject.parseObject(response, TpResultDTO.class);
            }
        } catch (Exception e) {
            log.error("修改设备名称异常 - 摄像头SN: {}, 设备名称: {}, 异常信息: {}", cameraSn, deviceName, e.getMessage());
        }
        return null;
    }
}
